var fdate_cal = null;
var tdate_cal = null;
var search_found_cache = null;

function init_search(){
	dwr.util.setValue('search_from_date','');
	dwr.util.setValue('search_to_date','');
	dwr.util.setValue('search_from_amt_range','');
	dwr.util.setValue('search_to_amt_range','');
	$('search_document_type').selectedIndex = 0;
	$('doc_recd_rdo').checked = false;
	$('doc_sent_rdo').checked = false;
	$('search_notfound').style.display='none';
	$('search_results').style.display='none';
	dwr.util.setValue('searchdoctype','');
	search_found_cache = null;
}
function open_search_page(){
	init_search();
	u_hideAllSections();
	u_safeShowElement('mainSearch_div');
	if(fdate_cal == null){
		fdate_cal = new JsDatePick({
			useMode:2,
			target:"search_from_date",
			dateFormat:"%m/%d/%Y",
			limitToToday:true,
			cellColorScheme:"aqua",
			dateFormat:"%m/%d/%Y",
			imgPath:"/thirdpartyscripts/jsdatepick/img/",
			weekStartDay:1
		});
	}
	
	if(tdate_cal == null){
		tdate_cal = new JsDatePick({
			useMode:2,
			target:"search_to_date",
			dateFormat:"%m/%d/%Y",
			limitToToday:true,
			cellColorScheme:"aqua",
			dateFormat:"%m/%d/%Y",
			imgPath:"/thirdpartyscripts/jsdatepick/img/",
			weekStartDay:1
		});
	}
	
	if(!isNavigationFromBackButton){
	var functionPointerObj = new Object();
	functionPointerObj.functionName = "open_search_page()";
	navigationStateArray.push(functionPointerObj);
	}
}

function do_search(){
	//Validate:
	var msg = new Array();
	var sentrecd = "";
	if(!$('doc_recd_rdo').checked && !$('doc_sent_rdo').checked){
		msg.push("Sent or Received is required.");
	}else{
		if($('doc_recd_rdo').checked){
			sentrecd = "RECD";
		}else{
			sentrecd = "SENT";
		}
	}
	
	var type = dwr.util.getValue('search_document_type');
	if(isEmptyString(trimString(type))){
		msg.push('Document Type is required.');
	}
	
	var fdatestr = dwr.util.getValue('search_from_date');
	var tdatestr = dwr.util.getValue('search_to_date');
	
	var fdate = null;
	var tdate = null;
	
	if(!isEmptyString(trimString(fdatestr))){
		try {
			fdate = new Date(fdatestr);
		}catch(ex){
			msg.push('From Date entered is not a valid date.');
		}
	}
	
	if(!isEmptyString(trimString(tdatestr))){
		try {
			tdate = new Date(tdatestr);
		}catch(ex){
			msg.push('To Date entered is not a valid date.');
		}
	}
	
	if(fdate != null && tdate != null){
		if(tdate < fdate){
			msg.push('To Date must be later than From Date.');
		}
	}
	
	var frmamtstr = dwr.util.getValue('search_from_amt_range');
	var toamtstr = dwr.util.getValue('search_to_amt_range');
	var frmamt = null;
	var toamt = null;
	if(!isEmptyString(trimString(frmamtstr))){
		if(isNaN(Number(frmamtstr))){
			msg.push('From amount is not a valid number.');
		}else{
			frmamt = Number(frmamtstr);
			if(frmamt <= 0){
				msg.push('From amount must be greater than zero.')
			}
		}
	}
	
	if(!isEmptyString(trimString(toamtstr))){
		if(isNaN(Number(toamtstr))){
			msg.push('To amount is not a valid number.');
		}else{
			toamt = Number(toamtstr);
			if(toamt <= 0){
				msg.push('To amount must be greater than zero.')
			}
		}
	}
	
	if(frmamt != null && toamt != null){
		if(toamt < frmamt){
			msg.push('To Amount must be greater than or equal to From Amount.');
		}
	}
	
	if(msg.length > 0){
		var msg2 = 'Search cannot be performed until the following errors are corrected:\n-- ' + msg.join('\n-- ');
		alert(msg2);
		return;
	}
	
	var searchObj = {
		sentReceived : sentrecd,
		documentType : type,
		fromDate : fdate,
		toDate : tdate,
		fromAmount : frmamt,
		toAmount : toamt,
		companyId : usr_comp_cache.companyId,
		companyUid : usrcompany_uid
	}
	
	var dcmd2 = {
			callback : success_searchdocument,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler
		};
	
	
	DWR_SearchService.searchDocuments(searchObj,dcmd2);
	
}

var found_yui_table_instance = null;
var foundcolumnDefs = [ {
	key : "orderNumber",
	label : "Document#",
	formatter : "hlinkFormatter",
	sortable : true
}, {
	key : "orderDate",
	label : "Document Date",
	formatter: "date",
	sortable : true
} , {
	key : "orderAmount",
	label : "Amount",
	formatter: "currency"
}];

function create_found_table(){
		var posDataSource = new YAHOO.util.DataSource();
		posDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
		found_yui_table_instance = new YAHOO.widget.DataTable('found_yui_table',foundcolumnDefs,posDataSource,{});
		found_yui_table_instance.set("selectionMode", "single");
}

function clear_found_table() {
	if (found_yui_table_instance != null) {
		var length = found_yui_table_instance.getRecordSet().getLength();
		if (length > 0) {
			found_yui_table_instance.deleteRows(0, length);
		}
	}
}

function alter_col_defs(documentType){
	if(documentType == "PO"){
		dwr.util.setValue('searchdoctype','Purchase Orders');
		foundcolumnDefs[0].key = "orderNumber";
		foundcolumnDefs[1].key = "orderDate";
		foundcolumnDefs[2].key = "orderAmount";
		//foundcolumnDefs[3].key = "versionNumber";
	}else if(documentType == "INV"){
		dwr.util.setValue('searchdoctype','Invoices');
		foundcolumnDefs[0].key = "invoiceNumber";
		foundcolumnDefs[1].key = "invoiceDate";
		foundcolumnDefs[2].key = "totalInvoiceAmount";
		//foundcolumnDefs[3].key = "invoiceVersion";
	}else if(documentType == "CMEMO"){
		dwr.util.setValue('searchdoctype','Credit Memos');
		foundcolumnDefs[0].key = "creditMemoNumber";
		foundcolumnDefs[1].key = "creditMemoDate";
		foundcolumnDefs[2].key = "totalCreditMemoAmount";
		//foundcolumnDefs[3].key = "creditMemoVersion";
	}else if(documentType == "PMT"){
		dwr.util.setValue('searchdoctype','Payments');
		foundcolumnDefs[0].key = "paymentNumber";
		foundcolumnDefs[1].key = "paymentDate";
		foundcolumnDefs[2].key = "totalPaymentAmount";
		//foundcolumnDefs[3].key = "paymentVersion";
	}
}


function success_searchdocument(dwrresp){
	var res = dwrresp.objRespOrError;
	if(res && res != null && res.results != null && res.results.length > 0){
		$('search_notfound').style.display='none';
		$('search_results').style.display='block';
		found_yui_table_instance = null;
		alter_col_defs(res.documentType);
		create_found_table();
		clear_found_table();
		found_yui_table_instance.addRows(res.results);
		search_found_cache = res;
	}else{
		$('search_notfound').style.display='block';
		$('search_results').style.display='none';
	}
}

